#include "gui.hpp"

using namespace cv;

Mat image;
Rect text_rect;

bool InitGUI(int width, int height)
{
    image.rows = height;
    image.cols = width;

    // 使用OpenCV创建窗口,窗口大小可变
    namedWindow("TimeNow", WINDOW_NORMAL);

    // 设置窗口大小
    resizeWindow("TimeNow", width, height);
    return true;
}

void DrawGUI(const std::string &time_stamp, int thickness_rate, Scalar bg_color, Scalar text_color)
{
    // 获取屏幕大小
    cv::Rect window_rect = cv::getWindowImageRect("TimeNow");
    cv::Size window_size(window_rect.width, window_rect.height);

    // 最小化时不渲染
    if (window_size.width == 0 || window_size.height == 0)
    {
        return;
    }

    // 清空图像
    image = Mat::zeros(window_size, CV_8UC3);
    for (int i = 0; i < image.rows; i++)
    {
        for (int j = 0; j < image.cols; j++)
        {
            image.at<Vec3b>(i, j) = Vec3b(bg_color[0], bg_color[1], bg_color[2]); // 使用传入的背景色
        }
    }

    // 根据窗口大小计算文本大小
    // 逐渐增加font_scale,直到文本适应窗口
    int baseline;
    int thickness = 3;
    int font_face = FONT_HERSHEY_SCRIPT_SIMPLEX;
    Size text_size;
    double font_scale = 0.1;
    while (text_size.width < window_rect.width && text_size.height < window_rect.height) // 文本尚未超出窗口
    {
        font_scale += 0.01; // 增加font_scale
        // 计算文本区域Rect
        text_size = getTextSize(time_stamp, font_face, font_scale, thickness, &baseline);
    }

    // 计算thickness
    thickness = text_size.width / thickness_rate;

    // 计算文本左上角坐标,使文本居中
    int x = (image.cols - text_size.width) / 2;
    int y = (image.rows + text_size.height) / 2;

    text_rect = Rect(x, y, text_size.width, text_size.height);

    Mat font = imread("C:/Windows/Fonts/arial.ttf", IMREAD_UNCHANGED);

    // 绘制时间戳文本
    putText(image, time_stamp, text_rect.tl(), font_face, font_scale,
            text_color, thickness, LINE_AA);

    // 显示图像
    imshow("TimeNow", image);
}

void EndGUI()
{
    destroyAllWindows();
}